package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.Users;
import org.example.models.R;
import org.example.service.UsersService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    UsersService usersService;

    @PostMapping("/login")
    public R login(String username, String password){
        QueryWrapper<Users> query = new QueryWrapper<>();
        query.lambda().eq(Users::getUsername, username);
        query.lambda().eq(Users::getPassword, password);
        Users users = usersService.getOne(query);
        System.out.println(users);
        if(users==null){
            return R.error("登录失败,用户名或密码错误");
        }
        String token = JwtUtils.generateToken(users.getId(), users.getUsername());//生成token,这里用的是用户id和用户名
        return R.success(200,"登录成功",token);
    }

    @GetMapping("/page")
    public R<Page<Users>> page(
            @RequestParam(name="current", defaultValue = "1") Integer current,
            @RequestParam(name="size", defaultValue = "2") Integer size,
            @RequestHeader String token,
            @RequestParam(name="username",required = false) String username){
//        if(token ==null || JwtUtils.isExpired(token)){
//
//        }
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();//查询条件
        if(username != null && username.length() > 0){
            queryWrapper.lambda().like(Users::getUsername,username);
        }
        Page<Users> page = new Page<>(current, size);
        page =usersService.page(page,queryWrapper);
        return R.success(page);
    }

    @PostMapping
    public R insert(@RequestBody Users users){
        usersService.save(users);
        return R.success();
    }

    @PutMapping
    public R update(@RequestBody Users users){
        usersService.updateById(users);
        return R.success();
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") String id){
        usersService.removeById(id);
        return R.success();
    }
}
